<template>
  <a-spin :spinning="loading">
    <div v-if="labelList.length" class="relation-label">
      <div v-for="item in labelList" :key="item.id">
        <a-dropdown :get-popup-container="(triggerNode: any) => triggerNode.parentNode">
          <div class="relation-label-wrap" @click="handleClick(item)">
            <div class="relation-label-item">
              <div class="relation-label-title" :title="item?.name">{{ item?.name }}</div>
              <div class="relation-label-features">
                <div class="icon-btn-list">
                  <a-button v-if="isEditable" type="text" class="icon-only-btn" @click.stop="handleUpdate(item)">
                    <i class="iconfont icon-edit-line"></i>
                  </a-button>
                  <a-button v-if="isEditable" type="text" class="icon-only-btn" @click.stop="handleDelete(item)">
                    <i class="iconfont icon-delete-bin-6-line"></i>
                  </a-button>
                </div>
              </div>
            </div>
          </div>

          <template #overlay>
            <div class="supernatant-wrap">
              <div class="supernatant-wrap-herder">与此关系标签关联的实体标签</div>
              <div class="supernatant-wrap-main">
                <ul>
                  <li>
                    <p>起始标签：</p>
                    <div :title="item?.beginLabelName">{{ item?.beginLabelName }}</div>
                  </li>
                  <li>
                    <p>终止标签：</p>
                    <div :title="item?.endLabelName">{{ item?.endLabelName }}</div>
                  </li>
                </ul>
              </div>
            </div>
          </template>
        </a-dropdown>
      </div>
    </div>

    <default-image v-else title="暂无内容" />
  </a-spin>

  <relation-label-form ref="relationLabelFormRef" :title="labelFormTitle" @on-submit="onRelationLabelFormSubmit" />
</template>

<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue'
  import { inject, Ref, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import { textLabelTagApi } from '@/services/index'

  import { useLabelResultListStore } from '../../dmp-text/store/index'
  import RelationLabelForm from '../RelationLabelForm.vue'
  import { MarkTaskLabelRes } from './types'

  export interface RelationLabelProps {
    taskInfo: any
    // 筛选值
    searchValue?: string
  }
  const props = withDefaults(defineProps<RelationLabelProps>(), {
    searchValue: ''
  })

  const emits = defineEmits<{
    (event: 'delete', data: any): void
    (event: 'update', data: any): void
    (event: 'clickLabel', data: any): void
  }>()

  // 是否可编辑
  const isEditable = inject<Ref<boolean>>('isEditable') || ref(true)

  const labelResultListStore = useLabelResultListStore()
  const relationLabelFormRef = ref<InstanceType<typeof RelationLabelForm>>()

  const labelFormTitle = ref('编辑关系标签')

  const labelList = ref<MarkTaskLabelRes[]>([])
  const { loading, runAsync: runGetLabelList } = useRequest(textLabelTagApi.relationList)
  const getLabelList = async (params?: any) => {
    const res: any = await runGetLabelList({
      name: props.searchValue,
      taskId: props.taskInfo.id,
      ...params
    })
    labelList.value = res.data
  }

  /**
   * 删除
   */
  const handleDelete = (item: any) => {
    Modal.confirm({
      title: '确认删除？',
      content: '当前标签及当前标注任务中使用此标签的标注信息将被删除，且不可恢复，请确认操作',
      centered: true,
      async onOk() {
        await deleteTag()
        emits('delete', item)
      }
    })

    const deleteTag = async () => {
      await textLabelTagApi.del(
        {},
        {
          urlParams: {
            id: item.id
          },
          isAddUid: true
        }
      )
      // 将标注结果中关于该标签的信息全部删除
      const result = labelResultListStore.relationResultList.filter(result => {
        return result.relationLabel.id === item.id
      })
      labelResultListStore.removeRelationResults(result)
      message.success('删除成功')
      getLabelList()
    }
  }

  /**
   * 编辑
   */
  const handleUpdate = (item: any) => {
    relationLabelFormRef.value?.open({
      id: item.id,
      name: item.name,
      startLabel: item.beginLabelId,
      endLabel: item.endLabelId,
      taskId: props.taskInfo.id
    })
  }
  // 关系标签表单提交
  const onRelationLabelFormSubmit = async (formState: any) => {
    try {
      const { data } = await textLabelTagApi.editRelation(
        {
          id: formState?.id,
          taskId: props.taskInfo.id,
          name: formState?.name,
          color: formState?.color,
          beginLabelId: formState?.startLabel,
          endLabelId: formState?.endLabel,
          type: 3
        },
        {
          isAddUid: true
        }
      )

      // 编辑成功同步更新标注结果中的关系标签
      labelResultListStore.relationResultList.forEach(item => {
        if (item.relationLabel.id === formState.id) {
          labelResultListStore.updateRelationResult(item, {
            ...item.relationLabel,
            id: formState.id,
            name: formState.name,
            color: formState.color
          })
        }
      })
      emits('update', data)
      relationLabelFormRef.value?.close()
      getLabelList()
      message.success('标签编辑成功')
    } catch (error: any) {
    } finally {
      relationLabelFormRef.value?.hideLoading()
    }
  }

  /**
   * 点击标签
   */
  const handleClick = (item: any) => {
    emits('clickLabel', item)
  }

  /**
   * 搜索
   */
  const handleSearch = (searchValue?: string) => {
    getLabelList({ name: searchValue })
  }

  defineExpose({
    search: handleSearch,
    getLabelList: getLabelList
  })
</script>

<style lang="less" scoped>
  .relation-label {
    display: flex;
    padding: 8px 0;
    width: 100%;
    flex-direction: column;
    gap: 4px 0;

    .relation-label-wrap {
      position: relative;
      display: flex;
      align-items: center;
      padding: 0 24px;
      height: 44px;
      cursor: pointer;
      flex-shrink: 0;

      &:hover {
        background: #f5f5f5;

        .icon-btn-list {
          display: flex !important;
        }
      }

      .relation-label-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 6px;
        width: 100%;
        height: 100%;
        border-radius: 6px;

        .relation-label-title {
          height: 36px;
          font-size: 14px;
          color: @text01;
          font-weight: 400;
          line-height: 36px;
          .elliptical-1();
        }

        .relation-label-features {
          margin-left: 4px;

          .icon-btn-list {
            display: none;
            gap: 0 16px;
          }
        }
      }
    }
  }

  .supernatant-wrap {
    width: 100%;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 3px 0 rgba(37, 37, 45, 0.14), 0 2px 8px 0 rgba(37, 37, 45, 0.14);

    .supernatant-wrap-herder {
      display: flex;
      align-items: center;
      padding: 0 24px;
      height: 28px;
      font-size: 12px;
      color: @text03;
      font-weight: 400;
      border-bottom: 0.5px solid #e8e9eb;
    }

    .supernatant-wrap-main {
      padding: 4px 24px;
      width: 100%;
      font-size: 14px;
      color: @text03;
      font-weight: 400;
      line-height: 22px;

      > ul {
        display: flex;
        width: 100%;
        flex-direction: column;
        gap: 4px 0;

        > li {
          display: flex;
          width: 100%;
          min-width: 0;
          line-height: 20px;

          > p {
            width: 70px;
            flex-shrink: 0;
          }

          > div {
            width: 200px;
            color: @text01;
            .elliptical-1();
          }
        }
      }
    }
  }
</style>
